﻿using System.CodeDom;
using System.CodeDom.Compiler;
using System.IO;

namespace InfoPathHelpers.CodeGeneration.Core
{
    public abstract class CodeDomCSharpGenerator
    {
        protected static void GenerateOutputFile(string fileName, CodeCompileUnit targetUnit)
        {
            var Provider = CodeDomProvider.CreateProvider("CSharp");
            var Options = new CodeGeneratorOptions();
            Options.BracingStyle = "C";
            using (var SourceWriter = new StreamWriter(fileName))
            {
                Provider.GenerateCodeFromCompileUnit(
                    targetUnit, SourceWriter, Options);
            }
        }

        public static string CreateValidIdentifier(string name)
        {
            //Compliant with item 2.4.2 of the C# specification
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions
                    .Regex(@"[^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Nl}\p{Mn}\p{Mc}\p{Cf}\p{Pc}\p{Lm}]");

            var CleanName = regex.Replace(name, "");
            //The identifier must start with a character or a "_"
            if (!char.IsLetter(CleanName, 0))
            {
                CleanName = string.Concat("_", CleanName);
            }

            Microsoft.CSharp.CSharpCodeProvider.CreateProvider("CSharp").CreateEscapedIdentifier(CleanName);

            return CleanName;
        }
    }
}
